### Copyright (C) 2002-2006 Stephen Kennedy <stevek@gnome.org>

### This program is free software; you can redistribute it and/or modify
### it under the terms of the GNU General Public License as published by
### the Free Software Foundation; either version 2 of the License, or
### (at your option) any later version.

### This program is distributed in the hope that it will be useful,
### but WITHOUT ANY WARRANTY; without even the implied warranty of
### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
### GNU General Public License for more details.

### You should have received a copy of the GNU General Public License
### along with this program; if not, write to the Free Software
### Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

### From meld/misc.py

import gtk

def position_menu_under_widget(menu, widget):
  container = widget.get_ancestor(gtk.Container)

  widget_width, widget_height = widget.size_request()
  menu_width, menu_height = menu.size_request()

  screen = menu.get_screen()
  monitor_num = screen.get_monitor_at_window(widget.window)
  if monitor_num < 0:
    monitor_num = 0
  monitor = screen.get_monitor_geometry(monitor_num)

  x, y = widget.window.get_origin()
  if widget.flags() & gtk.NO_WINDOW:
    x += widget.allocation.x
    y += widget.allocation.y

  if container.get_direction() == gtk.TEXT_DIR_LTR:
    x += widget.allocation.width - widget_width
  else:
    x += widget_width - menu_width

  if (y + widget.allocation.height + menu_height) <= monitor.y + monitor.height:
    y += widget.allocation.height
  elif (y - menu_height) >= monitor.y:
    y -= menu_height
  elif monitor.y + monitor.height - (y + widget.allocation.height) > y:
    y += widget.allocation.height
  else:
    y -= menu_height

  return (x, y, False)
